package com.atguigu.datastream.day07;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * ClassName: Flink08_KeyedState_ValueState
 * Package: com.atguigu.day07
 * Description:
 *              统计场景中，就是实时统计前几名。例如，针对每个传感器需要统计最高的三个水位值
 * @Author ChenJun
 * @Create 2023/4/14 19:43
 * @Version 1.0
 */
public class Flink09_KeyedState_ListState {
    public static void main(String[] args) throws Exception {

        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将数据转为JavaBean，为了方便提取数据
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorDStream.keyBy("id");


        // 5 TODO 需求：统计场景中，就是实时统计前几名。例如，针对每个传感器需要统计最高的三个水位值
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

           // 5.1 TODO 定义状态
            private ListState<Integer> listState;

            //5.2 TODO 初始化状态
            @Override
            public void open(Configuration parameters) throws Exception {
                listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listState", Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<Tuple, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {

                //获取到前三次的水位值
                Iterable<Integer> TOP3water = listState.get();

                //创建一个List集合用于排序
                ArrayList<Integer> sortList = new ArrayList<>();

                //迭代器遍历（盛放最高三个水位值）
                for (Integer vc : TOP3water) {
                    sortList.add(vc);
                }

                //将目前的值放到sortList中
                sortList.add(value.getVc());

                //将元素从大到小排序
                sortList.sort(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o2 -o1;
                    }
                });

                //判断sortList中是否大于3个数，删除最后一个，拿到最大的3个
                if (sortList.size() > 3 ){
                    sortList.remove(3);
                }

                //集合的数据更新到状态中
                listState.update(sortList);

                //将最大的3个水位值输出
                out.collect(sortList.toString());

            }
        }).print();


        env.execute();
    }
}
